package com.easychat.websocket.netty;

import com.easychat.redis.RedisComponent;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.annotation.Repeat;

import javax.annotation.Resource;

/**
 * @Author Dongdong
 * @注释 超时处理器
 */

public class HandlerHeartBeat extends ChannelDuplexHandler {

    private static  final Logger logger = LoggerFactory.getLogger(HandlerHeartBeat.class);
    @Resource
    private RedisComponent redisComponent;
    /**
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
    /**
     *  超时事件
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if ( evt instanceof IdleStateEvent){
            IdleStateEvent e = (IdleStateEvent) evt;//获取超时事件
            //如果是读超时
            if (e.state() == IdleState.READER_IDLE){
                logger.info("心跳超时");
                ctx.close();
            }else if (e.state() == IdleState.READER_IDLE){
                ctx.writeAndFlush("heart");
            }
        }
    }
}
